#!/usr/bin/env python3
"""
S3 Bucket Versioning Tool - GetBucketVersioning/PutBucketVersioning API 演示工具

这个工具演示如何使用版本控制相关的 API 管理桶的版本控制设置。

使用示例:
    python s3_bucket_versioning.py --name my-bucket --get
    python s3_bucket_versioning.py --name my-bucket --enable
    python s3_bucket_versioning.py --name my-bucket --suspend
    python s3_bucket_versioning.py --format json
    python s3_bucket_versioning.py --verbose
"""

import argparse
import boto3
import json
import sys
from datetime import datetime, timezone
from botocore.config import Config
from botocore.exceptions import ClientError, NoCredentialsError


class BucketVersioningClient:
    """S3 桶版本控制客户端"""
    
    def __init__(self, endpoint_url='http://localhost:8000', 
                 access_key='AKIAIOSFODNN7EXAMPLE', 
                 secret_key='wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
                 region='us-east-1'):
        """
        初始化桶版本控制客户端
        
        Args:
            endpoint_url: S3 服务端点
            access_key: AWS Access Key
            secret_key: AWS Secret Key
            region: AWS 区域
        """
        self.endpoint_url = endpoint_url
        self.access_key = access_key
        self.secret_key = secret_key
        self.region = region
        self._client = None
    
    def _get_client(self):
        """获取 S3 客户端"""
        if self._client is None:
            self._client = boto3.client(
                's3',
                endpoint_url=self.endpoint_url,
                aws_access_key_id=self.access_key,
                aws_secret_access_key=self.secret_key,
                region_name=self.region,
                config=Config(s3={'addressing_style': 'path'})
            )
        return self._client


    def get_versioning_status(self, bucket_name):
        """简单格式获取桶的版本控制状态"""
        try:
            s3_client = self._get_client()
            response = s3_client.get_bucket_versioning(Bucket=bucket_name)
            
            status = response.get('Status', 'Disabled')
            mfa_delete = response.get('MfaDelete', 'Disabled')
            
            print(f"📋 桶版本控制状态: {bucket_name}")
            print(f"   🔄 版本控制: {self._get_status_display(status)}")
            print(f"   🔐 MFA 删除: {self._get_status_display(mfa_delete)}")
            
            # 显示状态说明
            print(f"\n💡 状态说明:")
            if status == 'Enabled':
                print(f"   ✅ 版本控制已启用 - 对象的新版本会被保留")
            elif status == 'Suspended':
                print(f"   ⏸️  版本控制已暂停 - 新对象不会创建版本，但现有版本保留")
            else:
                print(f"   ❌ 版本控制未启用 - 对象只保留最新版本")
            
            return status
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            
            if error_code == 'NoSuchBucket':
                print(f"❌ 桶不存在: {bucket_name}")
            else:
                print(f"❌ 获取版本控制状态失败 [{error_code}]: {error_msg}")
            
            return None
        except NoCredentialsError:
            print("❌ 错误: 未找到 AWS 凭据")
            return None
        except Exception as e:
            print(f"❌ 未知错误: {e}")
            return None
    
    def get_versioning_status_verbose(self, bucket_name):
        """详细格式获取桶的版本控制状态"""
        try:
            s3_client = self._get_client()
            print("📋 桶版本控制状态详细信息:")
            print("=" * 50)
            print(f"   🗂️  桶名称: {bucket_name}")
            print(f"   🌐 区域: {self.region}")
            print(f"   🔗 服务端点: {self.endpoint_url}")
            print(f"   📅 查询时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            print()
            
            response = s3_client.get_bucket_versioning(Bucket=bucket_name)
            
            status = response.get('Status', 'Disabled')
            mfa_delete = response.get('MfaDelete', 'Disabled')
            
            print(f"   ✅ 版本控制状态查询成功")
            print(f"   🔄 版本控制: {self._get_status_display(status)}")
            print(f"   🔐 MFA 删除: {self._get_status_display(mfa_delete)}")
            
            # 显示状态说明
            print(f"\n   💡 状态说明:")
            if status == 'Enabled':
                print(f"      ✅ 版本控制已启用 - 对象的新版本会被保留")
            elif status == 'Suspended':
                print(f"      ⏸️  版本控制已暂停 - 新对象不会创建版本，但现有版本保留")
            else:
                print(f"      ❌ 版本控制未启用 - 对象只保留最新版本")
            
            print(f"   📊 查询完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            
            return status
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            
            print(f"   ❌ 查询失败:")
            print(f"      错误代码: {error_code}")
            print(f"      错误信息: {error_msg}")
            
            if error_code == 'NoSuchBucket':
                print(f"   📋 状态: 桶不存在")
            else:
                print(f"   📋 状态: 查询失败")
            
            return None
        except NoCredentialsError:
            print("   ❌ 错误: 未找到 AWS 凭据")
            return None
        except Exception as e:
            print(f"   ❌ 未知错误: {e}")
            return None
    
    def get_versioning_status_json(self, bucket_name):
        """JSON 格式获取桶的版本控制状态"""
        try:
            s3_client = self._get_client()
            response = s3_client.get_bucket_versioning(Bucket=bucket_name)
            
            status = response.get('Status', 'Disabled')
            mfa_delete = response.get('MfaDelete', 'Disabled')
            
            result = {
                "success": True,
                "bucket_name": bucket_name,
                "versioning_status": status,
                "mfa_delete": mfa_delete,
                "status_display": {
                    "versioning": self._get_status_display(status),
                    "mfa_delete": self._get_status_display(mfa_delete)
                },
                "query_time": datetime.now().isoformat()
            }
            
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return status
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            
            if error_code == 'NoSuchBucket':
                result = {
                    "success": False,
                    "bucket_name": bucket_name,
                    "error": "NoSuchBucket",
                    "error_message": "桶不存在",
                    "query_time": datetime.now().isoformat()
                }
            else:
                result = {
                    "success": False,
                    "bucket_name": bucket_name,
                    "error": error_code,
                    "error_message": error_msg,
                    "query_time": datetime.now().isoformat()
                }
            
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return None
        except NoCredentialsError:
            result = {
                "success": False,
                "error": "NoCredentials",
                "error_message": "未找到 AWS 凭据",
                "query_time": datetime.now().isoformat()
            }
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return None
        except Exception as e:
            result = {
                "success": False,
                "error": "Unknown",
                "error_message": str(e),
                "query_time": datetime.now().isoformat()
            }
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return None


    def set_versioning_status(self, bucket_name, status):
        """简单格式设置桶的版本控制状态"""
        try:
            s3_client = self._get_client()
            print(f"🔄 设置桶版本控制: {bucket_name}")
            print(f"   目标状态: {self._get_status_display(status)}")
            
            # 设置版本控制
            s3_client.put_bucket_versioning(
                Bucket=bucket_name,
                VersioningConfiguration={'Status': status}
            )
            
            print(f"✅ 版本控制状态设置成功")
            
            # 验证设置结果
            print(f"\n🔍 验证设置结果:")
            new_status = self.get_versioning_status(bucket_name)
            
            if new_status == status:
                print(f"✅ 验证成功，状态已更新为: {self._get_status_display(status)}")
            else:
                print(f"⚠️  验证结果与预期不符，当前状态: {self._get_status_display(new_status)}")
            
            return True
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            
            if error_code == 'NoSuchBucket':
                print(f"❌ 桶不存在: {bucket_name}")
            else:
                print(f"❌ 设置版本控制失败 [{error_code}]: {error_msg}")
            
            return False
        except NoCredentialsError:
            print("❌ 错误: 未找到 AWS 凭据")
            return False
        except Exception as e:
            print(f"❌ 未知错误: {e}")
            return False
    
    def set_versioning_status_verbose(self, bucket_name, status):
        """详细格式设置桶的版本控制状态"""
        try:
            s3_client = self._get_client()
            print("🔄 桶版本控制设置详细信息:")
            print("=" * 50)
            print(f"   🗂️  桶名称: {bucket_name}")
            print(f"   🌐 区域: {self.region}")
            print(f"   🔗 服务端点: {self.endpoint_url}")
            print(f"   📅 操作时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            print(f"   🎯 目标状态: {self._get_status_display(status)}")
            print()
            
            # 设置版本控制
            print(f"   🔧 正在设置版本控制状态...")
            s3_client.put_bucket_versioning(
                Bucket=bucket_name,
                VersioningConfiguration={'Status': status}
            )
            
            print(f"   ✅ 版本控制状态设置成功")
            
            # 验证设置结果
            print(f"\n   🔍 验证设置结果:")
            new_status = self.get_versioning_status_verbose(bucket_name)
            
            if new_status == status:
                print(f"   ✅ 验证成功，状态已更新为: {self._get_status_display(status)}")
            else:
                print(f"   ⚠️  验证结果与预期不符，当前状态: {self._get_status_display(new_status)}")
            
            print(f"   📊 操作完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            
            return True
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            
            print(f"   ❌ 设置失败:")
            print(f"      错误代码: {error_code}")
            print(f"      错误信息: {error_msg}")
            
            if error_code == 'NoSuchBucket':
                print(f"   📋 状态: 桶不存在")
            else:
                print(f"   📋 状态: 设置失败")
            
            return False
        except NoCredentialsError:
            print("   ❌ 错误: 未找到 AWS 凭据")
            return False
        except Exception as e:
            print(f"   ❌ 未知错误: {e}")
            return False
    
    def set_versioning_status_json(self, bucket_name, status):
        """JSON 格式设置桶的版本控制状态"""
        try:
            s3_client = self._get_client()
            
            # 设置版本控制
            s3_client.put_bucket_versioning(
                Bucket=bucket_name,
                VersioningConfiguration={'Status': status}
            )
            
            # 验证设置结果
            try:
                response = s3_client.get_bucket_versioning(Bucket=bucket_name)
                actual_status = response.get('Status', 'Disabled')
                verification_success = actual_status == status
            except:
                actual_status = None
                verification_success = False
            
            result = {
                "success": True,
                "bucket_name": bucket_name,
                "operation": "set_versioning",
                "target_status": status,
                "actual_status": actual_status,
                "verification_success": verification_success,
                "status_display": {
                    "target": self._get_status_display(status),
                    "actual": self._get_status_display(actual_status) if actual_status else "未知"
                },
                "operation_time": datetime.now().isoformat()
            }
            
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return True
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            
            if error_code == 'NoSuchBucket':
                result = {
                    "success": False,
                    "bucket_name": bucket_name,
                    "operation": "set_versioning",
                    "error": "NoSuchBucket",
                    "error_message": "桶不存在",
                    "operation_time": datetime.now().isoformat()
                }
            else:
                result = {
                    "success": False,
                    "bucket_name": bucket_name,
                    "operation": "set_versioning",
                    "error": error_code,
                    "error_message": error_msg,
                    "operation_time": datetime.now().isoformat()
                }
            
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return False
        except NoCredentialsError:
            result = {
                "success": False,
                "error": "NoCredentials",
                "error_message": "未找到 AWS 凭据",
                "operation_time": datetime.now().isoformat()
            }
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return False
        except Exception as e:
            result = {
                "success": False,
                "error": "Unknown",
                "error_message": str(e),
                "operation_time": datetime.now().isoformat()
            }
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return False


    def _get_status_display(self, status):
        """获取状态的友好显示"""
        status_map = {
            'Enabled': '✅ 启用',
            'Suspended': '⏸️  暂停', 
            'Disabled': '❌ 禁用'
        }
        return status_map.get(status, status)


    def show_versioning_info(self):
        """简单格式显示版本控制相关信息"""
        print("📚 S3 版本控制说明:")
        print("=" * 50)
        
        print("\n🔄 版本控制状态:")
        print("   ✅ Enabled  (启用)   - 为每个对象保留多个版本")
        print("   ⏸️  Suspended (暂停)  - 暂停版本控制，但保留现有版本")
        print("   ❌ Disabled  (禁用)   - 未启用版本控制（默认状态）")
        
        print("\n💡 版本控制的好处:")
        print("   • 🔒 数据保护 - 防止意外删除或修改")
        print("   • 📊 变更跟踪 - 跟踪对象的历史变更")
        print("   • 🔄 回滚能力 - 可以恢复到任意历史版本")
        print("   • 🛡️  合规要求 - 满足数据保留和审计要求")
        
        print("\n⚠️  注意事项:")
        print("   • 💰 存储成本 - 每个版本都会占用存储空间")
        print("   • 🗑️  删除复杂 - 需要显式删除所有版本")
        print("   • 📈 管理开销 - 需要管理版本生命周期")
        
        print("\n🎯 使用建议:")
        print("   • 重要数据桶建议启用版本控制")
        print("   • 配合生命周期策略自动清理旧版本")
        print("   • 定期审计版本使用情况")
    
    def show_versioning_info_verbose(self):
        """详细格式显示版本控制相关信息"""
        print("📚 S3 版本控制详细信息:")
        print("=" * 70)
        print(f"   🌐 区域: {self.region}")
        print(f"   🔗 服务端点: {self.endpoint_url}")
        print(f"   📅 查询时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print()
        
        print("   🔄 版本控制状态:")
        print("      ✅ Enabled  (启用)   - 为每个对象保留多个版本")
        print("      ⏸️  Suspended (暂停)  - 暂停版本控制，但保留现有版本")
        print("      ❌ Disabled  (禁用)   - 未启用版本控制（默认状态）")
        
        print("\n   💡 版本控制的好处:")
        print("      • 🔒 数据保护 - 防止意外删除或修改")
        print("      • 📊 变更跟踪 - 跟踪对象的历史变更")
        print("      • 🔄 回滚能力 - 可以恢复到任意历史版本")
        print("      • 🛡️  合规要求 - 满足数据保留和审计要求")
        
        print("\n   ⚠️  注意事项:")
        print("      • 💰 存储成本 - 每个版本都会占用存储空间")
        print("      • 🗑️  删除复杂 - 需要显式删除所有版本")
        print("      • 📈 管理开销 - 需要管理版本生命周期")
        
        print("\n   🎯 使用建议:")
        print("      • 重要数据桶建议启用版本控制")
        print("      • 配合生命周期策略自动清理旧版本")
        print("      • 定期审计版本使用情况")
    
    def show_versioning_info_json(self):
        """JSON 格式显示版本控制相关信息"""
        result = {
            "success": True,
            "operation": "versioning_info",
            "versioning_states": {
                "Enabled": {
                    "display": "✅ 启用",
                    "description": "为每个对象保留多个版本"
                },
                "Suspended": {
                    "display": "⏸️ 暂停",
                    "description": "暂停版本控制，但保留现有版本"
                },
                "Disabled": {
                    "display": "❌ 禁用",
                    "description": "未启用版本控制（默认状态）"
                }
            },
            "benefits": [
                "🔒 数据保护 - 防止意外删除或修改",
                "📊 变更跟踪 - 跟踪对象的历史变更",
                "🔄 回滚能力 - 可以恢复到任意历史版本",
                "🛡️ 合规要求 - 满足数据保留和审计要求"
            ],
            "considerations": [
                "💰 存储成本 - 每个版本都会占用存储空间",
                "🗑️ 删除复杂 - 需要显式删除所有版本",
                "📈 管理开销 - 需要管理版本生命周期"
            ],
            "recommendations": [
                "重要数据桶建议启用版本控制",
                "配合生命周期策略自动清理旧版本",
                "定期审计版本使用情况"
            ],
            "query_time": datetime.now().isoformat()
        }
        
        print(json.dumps(result, indent=2, ensure_ascii=False))
    
    def batch_versioning_operation(self, operation, bucket_names=None):
        """简单格式批量版本控制操作"""
        try:
            s3_client = self._get_client()
            # 如果没有指定桶名，获取所有桶
            if not bucket_names:
                response = s3_client.list_buckets()
                bucket_names = [bucket['Name'] for bucket in response['Buckets']]
            
            if not bucket_names:
                print("📭 没有找到桶")
                return True
            
            print(f"🔄 批量{operation}版本控制 ({len(bucket_names)} 个桶):")
            print("=" * 60)
            
            success_count = 0
            failed_buckets = []
            
            for bucket_name in bucket_names:
                print(f"\n📦 处理桶: {bucket_name}")
                
                if operation == "获取":
                    status = self.get_versioning_status(bucket_name)
                    if status is not None:
                        success_count += 1
                    else:
                        failed_buckets.append(bucket_name)
                elif operation in ["启用", "暂停"]:
                    target_status = "Enabled" if operation == "启用" else "Suspended"
                    if self.set_versioning_status_simple(bucket_name, target_status):
                        success_count += 1
                    else:
                        failed_buckets.append(bucket_name)
            
            # 显示汇总结果
            print(f"\n📊 批量操作结果:")
            print(f"   ✅ 成功: {success_count}/{len(bucket_names)}")
            print(f"   ❌ 失败: {len(failed_buckets)}/{len(bucket_names)}")
            
            if failed_buckets:
                print(f"   失败的桶: {', '.join(failed_buckets)}")
            
            return success_count == len(bucket_names)
            
        except Exception as e:
            print(f"❌ 批量操作失败: {e}")
            return False
    
    def batch_versioning_operation_verbose(self, operation, bucket_names=None):
        """详细格式批量版本控制操作"""
        try:
            s3_client = self._get_client()
            print(f"🔄 批量版本控制操作详细信息:")
            print("=" * 60)
            print(f"   🔧 操作类型: {operation}")
            print(f"   🌐 区域: {self.region}")
            print(f"   🔗 服务端点: {self.endpoint_url}")
            print(f"   📅 开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            print()
            
            # 如果没有指定桶名，获取所有桶
            if not bucket_names:
                response = s3_client.list_buckets()
                bucket_names = [bucket['Name'] for bucket in response['Buckets']]
            
            if not bucket_names:
                print("   📭 没有找到桶")
                return True
            
            print(f"   📚 发现 {len(bucket_names)} 个桶，开始批量操作:")
            print("   " + "=" * 60)
            
            success_count = 0
            failed_buckets = []
            
            for i, bucket_name in enumerate(bucket_names, 1):
                print(f"   [{i}/{len(bucket_names)}] 处理桶: {bucket_name}")
                
                if operation == "获取":
                    status = self.get_versioning_status_verbose(bucket_name)
                    if status is not None:
                        success_count += 1
                        print(f"   ✅ 成功")
                    else:
                        failed_buckets.append(bucket_name)
                        print(f"   ❌ 失败")
                elif operation in ["启用", "暂停"]:
                    target_status = "Enabled" if operation == "启用" else "Suspended"
                    if self.set_versioning_status_verbose(bucket_name, target_status):
                        success_count += 1
                        print(f"   ✅ 成功")
                    else:
                        failed_buckets.append(bucket_name)
                        print(f"   ❌ 失败")
                print()
            
            # 显示汇总结果
            print(f"   📊 批量操作统计:")
            print(f"      • 总数量: {len(bucket_names)}")
            print(f"      • 成功数: {success_count}")
            print(f"      • 失败数: {len(failed_buckets)}")
            print(f"      • 成功率: {(success_count/len(bucket_names))*100:.1f}%")
            
            if failed_buckets:
                print(f"      • 失败桶列表: {', '.join(failed_buckets)}")
            
            print(f"   📅 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            
            return success_count == len(bucket_names)
            
        except Exception as e:
            print(f"   ❌ 批量操作失败: {e}")
            return False
    
    def batch_versioning_operation_json(self, operation, bucket_names=None):
        """JSON 格式批量版本控制操作"""
        try:
            s3_client = self._get_client()
            # 如果没有指定桶名，获取所有桶
            if not bucket_names:
                response = s3_client.list_buckets()
                bucket_names = [bucket['Name'] for bucket in response['Buckets']]
            
            if not bucket_names:
                result = {
                    "success": True,
                    "operation": "batch_versioning",
                    "operation_type": operation,
                    "total_buckets": 0,
                    "message": "没有找到桶",
                    "operation_time": datetime.now().isoformat()
                }
                print(json.dumps(result, indent=2, ensure_ascii=False))
                return True
            
            results = []
            success_count = 0
            
            for bucket_name in bucket_names:
                bucket_result = {
                    "bucket_name": bucket_name,
                    "operation": operation
                }
                
                try:
                    if operation == "获取":
                        response = s3_client.get_bucket_versioning(Bucket=bucket_name)
                        status = response.get('Status', 'Disabled')
                        mfa_delete = response.get('MfaDelete', 'Disabled')
                        
                        bucket_result.update({
                            "success": True,
                            "versioning_status": status,
                            "mfa_delete": mfa_delete,
                            "status_display": {
                                "versioning": self._get_status_display(status),
                                "mfa_delete": self._get_status_display(mfa_delete)
                            }
                        })
                        success_count += 1
                        
                    elif operation in ["启用", "暂停"]:
                        target_status = "Enabled" if operation == "启用" else "Suspended"
                        s3_client.put_bucket_versioning(
                            Bucket=bucket_name,
                            VersioningConfiguration={'Status': target_status}
                        )
                        
                        # 验证设置结果
                        try:
                            response = s3_client.get_bucket_versioning(Bucket=bucket_name)
                            actual_status = response.get('Status', 'Disabled')
                            verification_success = actual_status == target_status
                        except:
                            actual_status = None
                            verification_success = False
                        
                        bucket_result.update({
                            "success": True,
                            "target_status": target_status,
                            "actual_status": actual_status,
                            "verification_success": verification_success,
                            "status_display": {
                                "target": self._get_status_display(target_status),
                                "actual": self._get_status_display(actual_status) if actual_status else "未知"
                            }
                        })
                        success_count += 1
                        
                except ClientError as e:
                    error_code = e.response['Error']['Code']
                    error_msg = e.response['Error']['Message']
                    bucket_result.update({
                        "success": False,
                        "error": error_code,
                        "error_message": error_msg
                    })
                except Exception as e:
                    bucket_result.update({
                        "success": False,
                        "error": "Unknown",
                        "error_message": str(e)
                    })
                
                results.append(bucket_result)
            
            # 输出汇总结果
            summary = {
                "success": success_count == len(bucket_names),
                "operation": "batch_versioning",
                "operation_type": operation,
                "total_buckets": len(bucket_names),
                "success_count": success_count,
                "failed_count": len(bucket_names) - success_count,
                "success_rate": f"{(success_count/len(bucket_names))*100:.1f}%",
                "results": results,
                "operation_time": datetime.now().isoformat()
            }
            
            print(json.dumps(summary, indent=2, ensure_ascii=False))
            return success_count == len(bucket_names)
            
        except Exception as e:
            error_result = {
                "success": False,
                "operation": "batch_versioning",
                "operation_type": operation,
                "error": "Unknown",
                "error_message": str(e),
                "operation_time": datetime.now().isoformat()
            }
            print(json.dumps(error_result, indent=2, ensure_ascii=False))
            return False


def parse_args():
    """解析命令行参数"""
    parser = argparse.ArgumentParser(
        description='S3 Bucket Versioning API 演示工具',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例:
  %(prog)s --name my-bucket --get           # 获取版本控制状态
  %(prog)s --name my-bucket --enable        # 启用版本控制
  %(prog)s --name my-bucket --suspend       # 暂停版本控制
  %(prog)s --all-buckets --get              # 获取所有桶的版本控制状态
  %(prog)s --info                           # 显示版本控制说明
  %(prog)s --format json                    # JSON 格式输出
  %(prog)s --verbose                        # 详细格式输出
  %(prog)s --access-key KEY --secret-key SECRET  # 指定凭据
        """
    )
    
    parser.add_argument(
        '--host',
        default='http://localhost:8000',
        help='S3 服务端点 (默认: http://localhost:8000)'
    )
    
    parser.add_argument(
        '--access-key',
        default='AKIAIOSFODNN7EXAMPLE',
        help='AWS Access Key (默认: 测试密钥)'
    )
    
    parser.add_argument(
        '--secret-key',
        default='wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
        help='AWS Secret Key (默认: 测试密钥)'
    )
    
    parser.add_argument(
        '--region',
        default='us-east-1',
        help='AWS 区域 (默认: us-east-1)'
    )
    
    parser.add_argument(
        '--format',
        choices=['simple', 'verbose', 'json'],
        default='simple',
        help='输出格式 (默认: simple)'
    )
    
    parser.add_argument(
        '--verbose',
        action='store_true',
        help='详细输出模式 (等同于 --format verbose)'
    )
    
    # 桶选择选项
    bucket_group = parser.add_mutually_exclusive_group()
    bucket_group.add_argument(
        '--name',
        help='要操作的桶名称'
    )
    
    bucket_group.add_argument(
        '--all-buckets',
        action='store_true',
        help='对所有桶执行操作'
    )
    
    # 操作选项
    operation_group = parser.add_mutually_exclusive_group()
    operation_group.add_argument(
        '--get',
        action='store_true',
        help='获取版本控制状态'
    )
    
    operation_group.add_argument(
        '--enable',
        action='store_true',
        help='启用版本控制'
    )
    
    operation_group.add_argument(
        '--suspend',
        action='store_true',
        help='暂停版本控制'
    )
    
    operation_group.add_argument(
        '--info',
        action='store_true',
        help='显示版本控制说明'
    )
    
    return parser.parse_args()


def main():
    """主函数"""
    args = parse_args()
    
    # 如果指定了 --verbose，覆盖 format 设置
    if args.verbose:
        args.format = 'verbose'
    
    # 创建客户端
    client = BucketVersioningClient(
        endpoint_url=args.host,
        access_key=args.access_key,
        secret_key=args.secret_key,
        region=args.region
    )
    
    # 参数验证
    if args.info:
        if args.format == 'simple':
            client.show_versioning_info_simple()
        elif args.format == 'verbose':
            client.show_versioning_info_verbose()
        elif args.format == 'json':
            client.show_versioning_info_json()
        sys.exit(0)
    
    if not (args.name or args.all_buckets):
        print("❌ 错误: 必须指定 --name 或 --all-buckets")
        sys.exit(1)
    
    if not (args.get or args.enable or args.suspend):
        print("❌ 错误: 必须指定操作: --get, --enable, 或 --suspend")
        sys.exit(1)
    
    success = True
    
    # 根据格式执行相应操作
    if args.all_buckets:
        if args.get:
            if args.format == 'simple':
                success = client.batch_versioning_operation_simple("获取")
            elif args.format == 'verbose':
                success = client.batch_versioning_operation_verbose("获取")
            elif args.format == 'json':
                success = client.batch_versioning_operation_json("获取")
        elif args.enable:
            if args.format == 'simple':
                success = client.batch_versioning_operation_simple("启用")
            elif args.format == 'verbose':
                success = client.batch_versioning_operation_verbose("启用")
            elif args.format == 'json':
                success = client.batch_versioning_operation_json("启用")
        elif args.suspend:
            if args.format == 'simple':
                success = client.batch_versioning_operation_simple("暂停")
            elif args.format == 'verbose':
                success = client.batch_versioning_operation_verbose("暂停")
            elif args.format == 'json':
                success = client.batch_versioning_operation_json("暂停")
    else:
        if args.get:
            if args.format == 'simple':
                status = client.get_versioning_status(args.name)
            elif args.format == 'verbose':
                status = client.get_versioning_status_verbose(args.name)
            elif args.format == 'json':
                status = client.get_versioning_status_json(args.name)
            success = status is not None
        elif args.enable:
            if args.format == 'simple':
                success = client.set_versioning_status_simple(args.name, 'Enabled')
            elif args.format == 'verbose':
                success = client.set_versioning_status_verbose(args.name, 'Enabled')
            elif args.format == 'json':
                success = client.set_versioning_status_json(args.name, 'Enabled')
        elif args.suspend:
            if args.format == 'simple':
                success = client.set_versioning_status_simple(args.name, 'Suspended')
            elif args.format == 'verbose':
                success = client.set_versioning_status_verbose(args.name, 'Suspended')
            elif args.format == 'json':
                success = client.set_versioning_status_json(args.name, 'Suspended')
    
    # 设置退出码
    sys.exit(0 if success else 1)


if __name__ == '__main__':
    main()
